import re
import glob
import os
import csv
from datetime import datetime

import numpy as np


'''
读取结果
'''
def read_d_result(file_name):
    files = glob.glob(file_name)
    file_name = os.path.abspath(files[-1])

    data_all = np.genfromtxt(file_name, delimiter=',')

    return data_all

'''
读取气动力数据（电压值）
'''
def read_d_aero(file_name):
    data_all = []
    with open(file_name, 'r') as f:
        
        lines = f.readlines()
        for i, line in enumerate(lines):
            data_col = []
            numbers = re.findall(r"-?\d+\.?\d*", line)
            for num in numbers:
                data_col.append(float(num))
            if data_col:
                data_all.append(data_col)
    data_all = np.array(data_all)
    return data_all


'''
读取绳拉力数据
'''
def read_d_tension(file_name):
    files = glob.glob(file_name)
    file_name = os.path.abspath(files[-1])

    data_all = np.genfromtxt(file_name, delimiter='	')

    return data_all


'''
读取绳长编码器数据
时间、8个理想绳长、8个实际绳长
'''
def read_d_encoder(file_name):
    files = glob.glob(file_name)
    file_name = os.path.abspath(files[-1])

    data_all = np.genfromtxt(file_name, delimiter='	')

    return data_all


'''
读取姿态角数据
Roll(deg),Pitch(deg),Yaw(deg),xAcc(g),yAcc(g),zAcc(g),xGyro(deg/s),yGyro(deg/s),zGyro(deg/s),Temperatrue,Timestamp,Time
'''
def read_d_angle(file_name):
    files = glob.glob(file_name)
    file_name = os.path.abspath(files[-1])

    data_all = np.genfromtxt(file_name, delimiter=',',skip_header=1)

    time_stamp = np.genfromtxt(file_name, delimiter=',', skip_header=1, dtype='str')
    time_stamp = time_stamp[:,-1]

    for i, t in enumerate(time_stamp):
        t = t.split("'")
        time_object = datetime.strptime(t[0], "%Y-%m-%d %H:%M:%S")
        numeric_format = int(time_object.strftime("%Y%m%d%H%M%S")) + float(t[1])/1000
        data_all[i,-1] = numeric_format

    data_all[:,2] = -data_all[:,2]
    return data_all


'''
按照文件名，读取文件夹下所有的试验项目
'''
def get_l_folder(file_dir):
    
    file_list = []
    file_list_temp = []
    
    
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            file_name, file_type = os.path.splitext(file)
            # print(file_name, file_type)
            if(file_type == ".TXT" or file_type == ".txt"):
                
                file_list_temp.append(file_name.split("_")[0])
    flag = [1]*len(file_list_temp)            
    
    # 检查重复
    for i, file_temp in enumerate(file_list_temp):
        if(file_list.count(file_temp)==0):
            file_list.append(file_temp)
        elif(file_list.count(file_temp)==1):
            flag[i] = 0
        else:
            flag[i] = 2
            
    print('文件数量: ' + str(len(file_list)))
    print(str(file_list))

    return file_list

'''
从试验项目表读取试验项目
'''
def get_l_list(model):
    file_name = "../DATASET_ALL/LIST/" + model + ".csv"

    file_list = []

    with open(file_name, 'r') as file:
        csv_reader = csv.reader(file)
        for row in csv_reader:
            file_list.append(row[0])
    
    print('文件数量: ' + str(len(file_list)))
    # print(str(file_list))

    return file_list


'''
获取运动频率，转换为频率字典
俯仰/滚转/偏航/
'''
def get_f(model, dataset_prefix):
    file_name = dataset_prefix + model + "/freq.csv"
    freq_dict = {}

    with open(file_name, 'r') as file:
        csv_reader = csv.reader(file)
        for j,row in enumerate(csv_reader):
            if j!=0:
                freq_dict[row[0]] = []
                
                for i,num in enumerate(row):
                    if i!=0 and num:
                        temp = freq_dict[row[0]]
                        temp.append(float(num))
                        freq_dict[row[0]] = temp

    return freq_dict